'use client';

import {
  type ChangeEvent,
  type FormEvent,
  useEffect,
  useRef,
  useState,
} from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import diff from 'microdiff';
import type { IDifference, IPostStyle, IQueryPostDetails } from '@/interfaces';
import type {
  TStyleBackgroundColorMode,
  TStyleColorMode,
  TStyleType,
} from '@/types';
import useToast from '@/hooks/useToast';
import { getDiffData, mergeObjects, toCamelCase } from '@/lib/tool';
import { BADGE_BACKGROUND_COLOR_MODE } from '@/lib/constant';
import IroItem from '@/app/[locale]/admin/forum/post/update/IroItem';
import {
  createPostStyle,
  queryAllPostStylePreset,
  removePostStyle,
  updatePostStyle,
} from '@/services/api';
import classNames from 'classnames';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import Box from '@/app/[locale]/admin/common/box';
import Spinner from '@/app/[locale]/component/spinner/spinner';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

const defaultForm: any = {
  name: '',
  type: 'PRESET',
  icons: [],
  styles: {},
  classes: [],
  colorMode: 'DEFAULT',
  color: '#ffffff',
  backgroundColorMode: 'DEFAULT',
  backgroundColor: '#000000',
  useStyle: false,
  useClass: false,
};

export default function UpdatePostStyle(
  this: any,
  {
    source,
    translatedFields,
  }: {
    source: IQueryPostDetails;
    translatedFields: PrefixedTTranslatedFields<'postAdminPage'>;
  },
) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    name?: string;
    type?: TStyleType;
    icons?: string[];
    styles?: Record<string, string>;
    classes?: string[];
    colorMode?: TStyleColorMode;
    color?: string;
    backgroundColorMode?: TStyleBackgroundColorMode;
    backgroundColor?: string;
    useStyle?: boolean;
    useClass?: boolean;
  }>(defaultForm);
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const [currentItem, setCurrentItem] = useState<IPostStyle>();
  const [currentRemoveItem, setCurrentRemoveItem] = useState<IPostStyle>();
  const selectColorModeRef = useRef<HTMLSelectElement>(null);
  const selectBackgroundColorModeRef = useRef<HTMLSelectElement>(null);
  const [selectColorMode, setSelectColorMode] = useState('HEX');
  const [selectBackgroundColorMode, setSelectBackgroundColorMode] =
    useState('HEX');
  const [usePreset, setUsePreset] = useState('-1');
  const [styleForm, setStyleForm] = useState({
    key: '',
    value: '',
  });
  const [isDisabledSave, setIsDisabledSave] = useState(true);

  const createPostStyleMutation = useMutation(createPostStyle);
  const updatePostStyleMutation = useMutation(updatePostStyle);
  const removePostStyleMutation = useMutation(removePostStyle);

  const queryAllPostStylePresetQuery = useQuery(
    ['/forum', '/styles', '/preset'],
    async () => {
      return (await queryAllPostStylePreset()) as IPostStyle[];
    },
  );

  useEffect(() => {
    let _form: any;
    if (currentItem) {
      _form = {
        name: currentItem.name,
        type: currentItem.type,
        icons: currentItem.icons,
        styles: currentItem.styles,
        classes: currentItem.classes,
        colorMode: currentItem.colorMode,
        color: currentItem.color,
        backgroundColorMode: currentItem.backgroundColorMode,
        backgroundColor: currentItem.backgroundColor,
        useStyle: currentItem.useStyle,
        useClass: currentItem.useClass,
      };
    } else {
      _form = defaultForm;
    }

    const diffData = diff(_form, form);
    setDifferenceData(diffData);
    setIsDisabledSave(diffData.length === 0);
  }, [currentItem, form]);

  function onChangeForm(
    e: ChangeEvent<HTMLSelectElement | HTMLTextAreaElement | HTMLInputElement>,
  ) {
    const name = e.target.name;
    const value = e.target.value;

    if (name === 'useStyle') {
      setForm({ ...form, useStyle: value === 'true' });
    } else if (name === 'useClass') {
      setForm({ ...form, useClass: value === 'true' });
    } else if (name === 'icons') {
      setForm({
        ...form,
        icons: value
          .replaceAll('，', ',')
          .split(',')
          .map((item) => item.trim()),
      });
    } else if (name === 'classes') {
      setForm({
        ...form,
        classes: value
          .replaceAll('，', ',')
          .split(',')
          .map((item) => item.trim()),
      });
    } else if (name === 'selectColorMode') {
      setSelectColorMode(value);
    } else if (name === 'selectBackgroundColorMode') {
      setSelectBackgroundColorMode(value);
    } else if (name === 'color') {
      setForm({
        ...form,
        [name]: value,
        useStyle: true,
        styles: { ...form.styles, color: value },
      });
    } else if (name === 'backgroundColor') {
      setForm({
        ...form,
        [name]: value,
        useStyle: true,
        styles: { ...form.styles, backgroundColor: value },
      });
    } else {
      setForm({ ...form, [name]: value });
    }
  }

  function onChangeUsePreset(e: ChangeEvent<HTMLSelectElement>) {
    const value = e.target.value;

    if (value === '-1') {
      setForm({
        ...mergeObjects(currentItem!, form),
        name: form.name,
        type: form.type,
      });
    } else if (queryAllPostStylePresetQuery.data) {
      const find = queryAllPostStylePresetQuery.data.find(
        (item) => item.id + '' === value,
      );
      if (find) {
        setForm({
          ...mergeObjects(find, form),
          name: form.name,
          type: form.type,
        });
      } else {
        show({
          type: 'DANGER',
          message: translatedFields.stylePage.defaultDoesNotExist,
        });
        return;
      }
    }

    setUsePreset(value);
  }

  function onChangeStyles(e: ChangeEvent<HTMLInputElement>) {
    const name = e.target.name;
    const value = e.target.value;
    setStyleForm({ ...styleForm, [name]: value });
  }

  function onClickDashStyle(key: string) {
    const styles = { ...form.styles };
    delete styles[key];
    setForm({
      ...form,
      styles,
    });
  }

  function onClickPlusStyle() {
    const { key, value } = styleForm;

    if (!key) {
      show({
        type: 'DANGER',
        message: translatedFields.stylePage.nameRequired,
      });
      return;
    }

    if (!value) {
      show({
        type: 'DANGER',
        message: translatedFields.stylePage.contentRequired,
      });
      return;
    }

    setForm({
      ...form,
      styles: { ...form.styles, [toCamelCase(key)]: value },
    });
    setStyleForm({
      key: '',
      value: '',
    });
  }

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      checkForm();

      const data = getDiffData(differenceData);

      if (currentItem) {
        if (
          data.type &&
          data.type === 'NAME' &&
          source.basic.styles.find((item) => item.type === data.type)
        ) {
          delete data.type;
        }

        data.icons = form.icons;
        data.styles = form.styles;
        data.classes = form.classes;

        if (data.type === 'NAME') {
          data.postId === source.basic.id;
        }

        await updatePostStyleMutation.mutateAsync({
          id: currentItem.id,
          data: data,
        });
      } else {
        await createPostStyleMutation.mutateAsync({
          data: {
            name: data.name,
            postId: source.basic.id,
            type: data.type ? data.type : 'PRESET',
          },
        });

        setForm(defaultForm);
      }

      await queryAllPostStylePresetQuery.refetch({ throwOnError: true });

      show({
        type: 'SUCCESS',
        message: translatedFields.saveCompleted,
      });
    } catch (e) {
      if (currentItem) {
        updatePostStyleMutation.reset();
      } else {
        createPostStyleMutation.reset();
      }

      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setDifferenceData([]);
      setCurrentItem(undefined);
    }
  }

  function onClickItem(item: IPostStyle) {
    setCurrentItem(item);
    setForm({
      ...form,
      ...{
        name: item.name,
        type: item.type,
        icons: item.icons,
        styles: item.styles,
        classes: item.classes,
        colorMode: item.colorMode,
        color: item.color,
        backgroundColorMode: item.backgroundColorMode,
        backgroundColor: item.backgroundColor,
        useStyle: item.useStyle,
        useClass: item.useClass,
      },
    });
  }

  function onClickCancel() {
    setCurrentItem(undefined);
    setForm({ ...form, ...defaultForm });
  }

  async function onClickRemove(item: IPostStyle) {
    try {
      setCurrentRemoveItem(item);

      await removePostStyleMutation.mutateAsync({
        id: item.id,
      });

      await queryAllPostStylePresetQuery.refetch({ throwOnError: true });

      show({
        type: 'SUCCESS',
        message: translatedFields.deleteCompleted,
      });
    } catch (e) {
      removePostStyleMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      setDifferenceData([]);
      setCurrentItem(undefined);
      setCurrentRemoveItem(undefined);
    }
  }

  function checkForm() {
    const name = form.name;

    if (!name) {
      throw translatedFields.stylePage.nameRequired;
    }

    if (
      !currentItem &&
      form.type === 'NAME' &&
      source.basic.styles.find((item) => item.type === 'NAME')
    ) {
      throw translatedFields.stylePage.styleTypeAlreadyExists;
    }
  }

  function changeColorCallback(color: string) {
    if (!color) {
      return;
    }

    setForm({
      ...form,
      color,
      useStyle: true,
      styles: { ...form.styles, color },
    });
  }

  function changeBackgroundColorCallback(color: string) {
    if (!color) {
      return;
    }

    setForm({
      ...form,
      backgroundColor: color,
      useStyle: true,
      styles: { ...form.styles, backgroundColor: color },
    });
  }

  if (queryAllPostStylePresetQuery.data) {
    const data = [...queryAllPostStylePresetQuery.data, ...source.basic.styles];

    return (
      <Box>
        <div className="vstack gap-4">
          {data.length > 0 && (
            <div className="table-responsive">
              <table className="table table-hover align-middle">
                <thead>
                  <tr className="text-nowrap">
                    <th scope="col" className="fw-normal">
                      {translatedFields.stylePage.name}
                    </th>
                    <th scope="col" className="fw-normal">
                      {translatedFields.stylePage.type}
                    </th>
                    <th scope="col" className="fw-normal">
                      {translatedFields.stylePage.color}
                    </th>
                    <th scope="col" className="fw-normal">
                      {translatedFields.stylePage.backgroundColor}
                    </th>
                    <th scope="col" className="fw-normal">
                      {translatedFields.stylePage.useClassName}
                    </th>
                    <th scope="col" className="fw-normal">
                      {translatedFields.stylePage.useStyle}
                    </th>
                    <th scope="col" className=""></th>
                  </tr>
                </thead>
                <tbody>
                  {data.map((item) => {
                    return (
                      <tr
                        key={item.id}
                        className={classNames('text-nowrap', {
                          'table-active':
                            currentItem && currentItem.id === item.id,
                        })}
                      >
                        <td
                          className="cursor-pointer"
                          onClick={onClickItem.bind(this, item)}
                        >
                          <div
                            className={classNames(
                              item.useClass &&
                                item.classes &&
                                item.classes.length > 0
                                ? item.classes
                                : false,
                              'hstack gap-2',
                            )}
                            style={
                              item.useStyle &&
                              item.styles &&
                              Object.keys(item.styles).length > 0
                                ? item.styles
                                : {}
                            }
                          >
                            {item.icons.map((value) => {
                              return (
                                <i
                                  key={value}
                                  className={classNames('bi', `bi-${value}`)}
                                ></i>
                              );
                            })}
                            <span>{item.name}</span>
                          </div>
                        </td>
                        <td
                          className="cursor-pointer"
                          onClick={onClickItem.bind(this, item)}
                        >
                          {translatedFields.stylePage.STYLE_TYPE[item.type]}
                        </td>
                        <td
                          className="cursor-pointer"
                          onClick={onClickItem.bind(this, item)}
                        >
                          {item.color
                            ? `${
                                translatedFields.stylePage.STYLE_COLOR_MODE[
                                  item.colorMode
                                ]
                              } (${item.color})`
                            : translatedFields.stylePage.STYLE_COLOR_MODE[
                                item.colorMode
                              ]}
                        </td>
                        <td
                          className="cursor-pointer"
                          onClick={onClickItem.bind(this, item)}
                        >
                          {item.backgroundColor
                            ? `${
                                translatedFields.stylePage.STYLE_COLOR_MODE[
                                  item.backgroundColorMode
                                ]
                              } (${item.backgroundColor})`
                            : translatedFields.stylePage.STYLE_COLOR_MODE[
                                item.backgroundColorMode
                              ]}
                        </td>
                        <td
                          className="cursor-pointer"
                          onClick={onClickItem.bind(this, item)}
                        >
                          {item.useClass
                            ? translatedFields.yes
                            : translatedFields.no}
                        </td>
                        <td
                          className="cursor-pointer"
                          onClick={onClickItem.bind(this, item)}
                        >
                          {item.useStyle
                            ? translatedFields.yes
                            : translatedFields.no}
                        </td>
                        <td>
                          {currentItem && currentItem.id === item.id && (
                            <button
                              onClick={onClickCancel}
                              className="btn btn-sm btn-light me-2"
                              type="button"
                            >
                              {translatedFields.cancel}
                            </button>
                          )}

                          <button
                            disabled={
                              currentRemoveItem &&
                              currentRemoveItem.id === item.id &&
                              removePostStyleMutation.isLoading
                            }
                            onClick={onClickRemove.bind(this, item)}
                            className="btn btn-sm btn-danger"
                            type="button"
                          >
                            {currentRemoveItem &&
                            currentRemoveItem.id === item.id &&
                            removePostStyleMutation.isLoading ? (
                              <span
                                className="spinner-border spinner-border-sm me-2"
                                role="status"
                                aria-hidden="true"
                              ></span>
                            ) : (
                              <i className="bi bi-trash me-2"></i>
                            )}
                            {translatedFields.delete}
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}

          {form.name && (
            <div className="card position-relative">
              <div className="card-body text-center">
                <div
                  className="position-absolute text-secondary"
                  style={{
                    left: '-1rem',
                    top: '-0.7rem',
                    transform: 'skew(15deg)',
                  }}
                >
                  {translatedFields.preview}
                </div>
                <div
                  className={classNames(
                    form.useClass && form.classes && form.classes.length > 0
                      ? form.classes
                      : false,
                    'hstack gap-2 justify-content-center',
                  )}
                  style={
                    form.useStyle &&
                    form.styles &&
                    Object.keys(form.styles).length > 0
                      ? form.styles
                      : {}
                  }
                >
                  {(form.icons || []).map((value) => {
                    return (
                      <i
                        key={value}
                        className={classNames('bi', `bi-${value}`)}
                      ></i>
                    );
                  })}
                  <span>{source.basic.name}</span>
                </div>
              </div>
            </div>
          )}

          <form onSubmit={onClickSave} className="vstack gap-4">
            {currentItem && currentItem.type !== 'PRESET' && (
              <div>
                <label className="form-label">
                  {translatedFields.stylePage.useDefault}
                </label>
                <select
                  name="usePreset"
                  value={usePreset}
                  onChange={onChangeUsePreset}
                  className="form-select"
                  aria-label="usePreset"
                  placeholder={translatedFields.stylePage.useDefaultPlaceholder}
                >
                  <option value="-1">
                    {translatedFields.stylePage.default}
                  </option>
                  {queryAllPostStylePresetQuery.data.map((item) => {
                    return (
                      <option key={item.id} value={item.id + ''}>
                        {item.name}
                      </option>
                    );
                  })}
                </select>
              </div>
            )}

            <div>
              <label className="form-label">
                {translatedFields.stylePage.name}
              </label>
              <input
                type="text"
                className="form-control"
                name="name"
                value={form.name}
                onChange={onChangeForm}
                aria-describedby="name"
                placeholder={translatedFields.stylePage.namePlaceholder}
              />
            </div>

            <div>
              <label className="form-label">
                {translatedFields.stylePage.type}
              </label>
              <select
                name="type"
                value={form.type}
                onChange={onChangeForm}
                className="form-select"
                aria-label="type"
                placeholder={translatedFields.stylePage.typePlaceholder}
              >
                <option value="PRESET">
                  {translatedFields.stylePage.preset}
                </option>
                <option value="NAME">{translatedFields.stylePage.name}</option>
              </select>
            </div>

            {currentItem && (
              <>
                <div>
                  <label className="form-label">
                    {translatedFields.stylePage.colorMode}
                  </label>
                  <div className="form-control user-select-none">
                    {['DEFAULT', 'CUSTOM'].map((item) => {
                      return (
                        <div
                          key={item}
                          className="form-check form-check-inline"
                        >
                          <input
                            id={`yw-badge-colorMode-${item}`}
                            name="colorMode"
                            className="form-check-input"
                            type="radio"
                            onChange={onChangeForm}
                            value={item}
                            checked={form.colorMode === item}
                          />
                          <label
                            className="form-check-label"
                            htmlFor={`yw-badge-colorMode-${item}`}
                          >
                            {
                              (translatedFields as any).stylePage
                                .STYLE_COLOR_MODE[item]
                            }
                          </label>
                        </div>
                      );
                    })}
                  </div>
                </div>

                {form.colorMode === 'CUSTOM' && (
                  <div>
                    <label className="form-label">
                      {translatedFields.stylePage.color}
                    </label>
                    <div className="row align-items-center gap-4">
                      <div className="col-4">
                        <div className="vstack gap-4">
                          <div className="row gap-4 align-items-center">
                            <div className="col-2"></div>
                            <div className="col">
                              <select
                                ref={selectColorModeRef}
                                name="selectColorMode"
                                value={selectColorMode}
                                onChange={onChangeForm}
                                className="form-select"
                                aria-label="selectColorMode"
                                placeholder={
                                  translatedFields.stylePage
                                    .colorOutputTypePlaceholder
                                }
                              >
                                <option value="HEX">HEX</option>
                                <option value="RGB">RGB</option>
                                <option value="RGBA">RGBA</option>
                                <option value="HSL">HSL</option>
                                <option value="HSLA">HSLA</option>
                              </select>
                            </div>
                          </div>

                          <input
                            type="text"
                            className="form-control"
                            name="color"
                            value={form.color}
                            onChange={onChangeForm}
                            aria-describedby="color"
                            placeholder={
                              translatedFields.stylePage.colorPlaceholder
                            }
                          />

                          <div className="form-text">
                            {translatedFields.stylePage.sliderBarPlaceholder}
                          </div>
                        </div>
                      </div>
                      <div className="col-7">
                        <IroItem
                          inputColor={form.color}
                          selectColorModeRef={selectColorModeRef}
                          changeColorCallback={changeColorCallback}
                        />
                      </div>
                    </div>
                  </div>
                )}

                {form.name &&
                  (form.colorMode === 'CUSTOM' ||
                    form.backgroundColorMode === 'CUSTOM') && (
                    <div className="card position-relative">
                      <div className="card-body text-center">
                        <div
                          className="position-absolute text-secondary"
                          style={{
                            left: '-1rem',
                            top: '-0.7rem',
                            transform: 'skew(15deg)',
                          }}
                        >
                          {translatedFields.preview}
                        </div>
                        <div
                          className={classNames(
                            form.useClass &&
                              form.classes &&
                              form.classes.length > 0
                              ? form.classes
                              : false,
                            'hstack gap-2 justify-content-center',
                          )}
                          style={
                            form.useStyle &&
                            form.styles &&
                            Object.keys(form.styles).length > 0
                              ? form.styles
                              : {}
                          }
                        >
                          {(form.icons || []).map((value) => {
                            return (
                              <i
                                key={value}
                                className={classNames('bi', `bi-${value}`)}
                              ></i>
                            );
                          })}
                          <span>{source.basic.name}</span>
                        </div>
                      </div>
                    </div>
                  )}

                <div>
                  <label className="form-label">
                    {translatedFields.stylePage.backgroundColorMode}
                  </label>
                  <div className="form-control user-select-none">
                    {Object.keys(BADGE_BACKGROUND_COLOR_MODE).map((item) => {
                      return (
                        <div
                          key={item}
                          className="form-check form-check-inline"
                        >
                          <input
                            id={`yw-badge-backgroundColorMode-${item}`}
                            name="backgroundColorMode"
                            className="form-check-input"
                            type="radio"
                            onChange={onChangeForm}
                            value={item}
                            checked={form.backgroundColorMode === item}
                          />
                          <label
                            className="form-check-label"
                            htmlFor={`yw-badge-backgroundColorMode-${item}`}
                          >
                            {BADGE_BACKGROUND_COLOR_MODE[item]}
                          </label>
                        </div>
                      );
                    })}
                  </div>
                </div>

                {form.backgroundColorMode === 'CUSTOM' && (
                  <div>
                    <label className="form-label">
                      {' '}
                      {translatedFields.stylePage.backgroundColor}
                    </label>
                    <div className="row align-items-center gap-4">
                      <div className="col-4">
                        <div className="vstack gap-4">
                          <div className="row gap-4 align-items-center">
                            <div className="col-2"></div>
                            <div className="col">
                              <select
                                ref={selectBackgroundColorModeRef}
                                name="selectBackgroundColorMode"
                                value={selectBackgroundColorMode}
                                onChange={onChangeForm}
                                className="form-select"
                                aria-label="selectBackgroundColorMode"
                                placeholder={
                                  translatedFields.stylePage
                                    .backgroundColorOutputTypePlaceholder
                                }
                              >
                                <option value="HEX">HEX</option>
                                <option value="RGB">RGB</option>
                                <option value="RGBA">RGBA</option>
                                <option value="HSL">HSL</option>
                                <option value="HSLA">HSLA</option>
                              </select>
                            </div>
                          </div>

                          <input
                            type="text"
                            className="form-control"
                            name="backgroundColor"
                            value={form.backgroundColor}
                            onChange={onChangeForm}
                            aria-describedby="backgroundColor"
                            placeholder={
                              translatedFields.stylePage
                                .backgroundColorPlaceholder
                            }
                          />

                          <div className="form-text">
                            {translatedFields.stylePage.sliderBarPlaceholder}
                          </div>
                        </div>
                      </div>
                      <div className="col-7">
                        <IroItem
                          inputColor={form.backgroundColor}
                          selectColorModeRef={selectBackgroundColorModeRef}
                          changeColorCallback={changeBackgroundColorCallback}
                        />
                      </div>
                    </div>
                  </div>
                )}

                <div>
                  <label className="form-label">
                    <span>{translatedFields.stylePage.icon}</span>
                    <span className="ms-2">
                      (
                      <a target="_blank" href="https://icons.getbootstrap.com">
                        {translatedFields.stylePage.clickViewIcon}
                      </a>
                      )
                    </span>
                  </label>
                  <textarea
                    rows={1}
                    className="form-control"
                    name="icons"
                    value={form.icons?.join(', ')}
                    onChange={onChangeForm}
                    aria-describedby="icons"
                    placeholder={translatedFields.stylePage.iconPlaceholder}
                  />
                </div>

                <div>
                  <label className="form-label">
                    {translatedFields.stylePage.useClassName}
                  </label>
                  <select
                    name="useClass"
                    value={form.useClass + ''}
                    onChange={onChangeForm}
                    className="form-select"
                    aria-label="useClass"
                    placeholder={
                      translatedFields.stylePage.useClassNamePlaceholder
                    }
                  >
                    <option value="false">{translatedFields.no}</option>
                    <option value="true">{translatedFields.yes}</option>
                  </select>
                </div>

                {form.useClass && (
                  <div>
                    <label className="form-label">
                      {translatedFields.stylePage.useClassName}
                    </label>
                    <textarea
                      rows={1}
                      className="form-control"
                      name="classes"
                      value={form.classes?.join(', ')}
                      onChange={onChangeForm}
                      aria-describedby="classes"
                      placeholder={
                        translatedFields.stylePage.useClassNameInputPlaceholder
                      }
                    />
                  </div>
                )}

                <div>
                  <label className="form-label">
                    {translatedFields.stylePage.useStyle}
                  </label>
                  <select
                    name="useStyle"
                    value={form.useStyle + ''}
                    onChange={onChangeForm}
                    className="form-select"
                    aria-label="useStyle"
                    placeholder={translatedFields.stylePage.useStylePlaceholder}
                  >
                    <option value="false">{translatedFields.no}</option>
                    <option value="true">{translatedFields.yes}</option>
                  </select>
                </div>

                {form.useStyle && (
                  <div className="vstack gap-2">
                    <div>
                      <label className="form-label">
                        {translatedFields.stylePage.useStyle}
                      </label>
                      <div className="vstack gap-2">
                        {form.styles &&
                          Object.keys(form.styles).map((value) => {
                            return (
                              <div key={value} className="hstack gap-4">
                                <input
                                  readOnly
                                  type="text"
                                  className="form-control"
                                  name="key"
                                  value={value}
                                  aria-describedby="key"
                                />
                                <input
                                  readOnly
                                  type="text"
                                  className="form-control"
                                  name="value"
                                  value={(form.styles || {})[value] || ''}
                                  aria-describedby="value"
                                />
                                <button
                                  onClick={onClickDashStyle.bind(this, value)}
                                  type="button"
                                  className="btn w-25 btn-danger"
                                >
                                  <i className="bi bi-dash-lg"></i>
                                </button>
                              </div>
                            );
                          })}
                      </div>
                    </div>
                    <div className="hstack gap-4 mb-4">
                      <input
                        type="text"
                        className="form-control"
                        name="key"
                        value={styleForm.key}
                        onChange={onChangeStyles}
                        aria-describedby="key"
                        placeholder={translatedFields.stylePage.nameCamelCase}
                      />
                      <input
                        type="text"
                        className="form-control"
                        name="value"
                        value={styleForm.value}
                        onChange={onChangeStyles}
                        aria-describedby="value"
                        placeholder={
                          translatedFields.stylePage.contentPlaceholder
                        }
                      />
                      <button
                        onClick={onClickPlusStyle}
                        type="button"
                        className="btn w-25 btn-primary"
                      >
                        <i className="bi bi-plus-lg"></i>
                      </button>
                    </div>
                  </div>
                )}
              </>
            )}

            <button
              type="submit"
              disabled={
                createPostStyleMutation.isLoading ||
                updatePostStyleMutation.isLoading ||
                isDisabledSave
              }
              className="btn btn-success col col-lg-2 my-4"
            >
              {(createPostStyleMutation.isLoading ||
                updatePostStyleMutation.isLoading) && <Spinner classs="me-2" />}
              {currentItem ? translatedFields.update : translatedFields.add}
            </button>
          </form>
        </div>
      </Box>
    );
  }

  if (queryAllPostStylePresetQuery.error) {
    return <Alert message={queryAllPostStylePresetQuery.error} type="error" />;
  }

  return <AlertLoad />;
}
